﻿using System;
using System.Windows.Forms;
using DevExpress.XtraBars;
using LayerEntity.Persona;
using LayerEntity.Sistema;
using LayerLogic;
using Shared;
using LayerEntity.Persona.RecursosHumanos;

namespace System2012.Persona.Empleados
{
    public partial class MantenimientoEmpleados : DevExpress.XtraEditors.XtraForm 
    {
        public MantenimientoEmpleados()
        {
            this.InitializeComponent();
            SystemUtils.RecordManagerPersona.UpdateList += new LayerLogic.Persona.LPersona.AddObject(UpdateGrillaEmpleados);
        }
        #region Metodos
        void RefreshLista() {
            gridControl1.DataSource = SystemUtils.RecordManagerPersona.GetEmployee();
            gridControl1.RefreshDataSource();
        }

        private void UpdateGrillaEmpleados(string msj, LayerLogic.EnumOperaciones op)
        {
            this.RefreshLista();
        }

        void NuevoEmpleado()
        {
            Empleado p = new Empleado();
            p.NuevoEmpleado();
            p.ShowDialog();
        }

        void EditarEmpleado()
        {
            if (gridView1.RowCount > 0)
            {
                IEPersona emp = (IEPersona)gridView1.GetFocusedRow();
                Empleado fr = new Empleado(emp);
                //fr.SetEmpleado(emp);
                fr.ShowDialog();
            }
        }

        private void ViewAcountInfo()
        {
            if (gridView1.RowCount > 0)
            {
                IEPersona p = (IEPersona)gridView1.GetFocusedRow();
                if (p != null)
                {
                    MantenimientoCuentasBancarias mb = new MantenimientoCuentasBancarias(p);
                    mb.ShowDialog();
                    SystemUtils.RecordManagerPersona.AddEmpleado(p);
                }
            }
            else {
                SystemUtils.AlerMessaje("No hay Registros de Empleados");
            }
        }

        #endregion
        private void ItemClickViewForm(object sender, ItemClickEventArgs e)
        {
            if ((string)e.Item.Tag == "NuevoEmpleado")
            {
                CheckExistsForms.ActivateForm<Empleado>();
            }
        }

        private void MantenimientoEmpleados_Load(object sender, EventArgs e)
        {
            this.Size = new System.Drawing.Size(this.MdiParent.Size.Width, this.MdiParent.Size.Height);
            this.Location = new System.Drawing.Point(this.MdiParent.Location.X, this.MdiParent.Location.Y);
            
            BGWLoadEmpleados.RunWorkerAsync();
        }

        private void CombinarRibbon(object sender, DevExpress.XtraBars.Ribbon.RibbonMergeEventArgs e)
        {
            e.MergedChild.BringToFront();
        }

        private void ItemClickVerForm(object sender, ItemClickEventArgs e)
        {
            if (e.Item.Tag != null)
            {
                if ((string)e.Item.Tag == "NuevoEmpleado")
                {
                    NuevoEmpleado();
                }
                if ((string)e.Item.Tag == "LoadAll")
                {
                    intLoadAll = 1;
                    if (!BGWLoadEmpleados.IsBusy) BGWLoadEmpleados.RunWorkerAsync();
                }
                if ((string)e.Item.Tag == "Exportar")
                {
                    if (gridView1.RowCount > 0)
                    {
                        SystemUtils.Exportar("Empleados", gridControl1);
                    }
                    else
                    {
                        SystemUtils.AlerMessaje("No hay Datos a Exportar");
                    }
                }
                if ((string)e.Item.Tag == "Editar")
                {

                    EditarEmpleado();
                }
                if ((string)e.Item.Tag == "Cuentas")
                {
                    ViewAcountInfo();
                }

                if ((string)e.Item.Tag == "ConvertToClient")
                {
                    IEPersona per = ObjectFactoryPersona.ConvertTo((IEPersona)gridView1.GetFocusedRow(), EnumTipoPersona.Cliente );
                    if (per != null)
                    {
                        if (string.IsNullOrEmpty(per.FullName.Trim())) {
                            per.FullName = string.Concat(per.Apellidos, ", ", per.Nombres);
                        }                        
                        if (SystemUtils.RecordManagerPersona.SaveClientes(per, EnumOperaciones.Actualizar) != string.Empty)
                        {
                            SystemUtils.RecordManagerPersona.AddCliente(per);
                        }
                    }
                }
                if ((string)e.Item.Tag == "ConvertToSupplier")
                {
                    IEPersona per = ObjectFactoryPersona.ConvertTo((IEPersona)gridView1.GetFocusedRow(), EnumTipoPersona.Proveedor);
                    if (per != null)
                    {
                        if (string.IsNullOrEmpty(per.FullName.Trim()))
                        {
                            per.FullName = string.Concat(per.Apellidos, ", ", per.Nombres);
                        }                        
                        if (SystemUtils.RecordManagerPersona.SaveProveedores(per, EnumOperaciones.Actualizar) != "")
                        {
                            SystemUtils.RecordManagerPersona.AddProveedor(per);
                        }
                    }
                }
            }
        }

        #region Procesos Background
        int intLoadAll = 0;
        private void BgwLoadEmpleadosDoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            BGWLoadEmpleados.ReportProgress(20, "Load Empleados");
            if (intLoadAll == 0)
            {
                SystemUtils.RecordManagerPersona.GetEmpleados(100);
            }
            else {
                SystemUtils.RecordManagerPersona.GetEmpleados(0);
            }
            BGWLoadEmpleados.ReportProgress(100, "Load Complete");
        }
       
        private void BgwLoadEmpleadosRunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            RefreshLista();
            if (intLoadAll != 0)
            {
                SystemUtils.InformationMessaje("Proceso Completado");
            }
        }

        private void BgwLoadEmpleadosProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            BarraProgreso.Caption = e.UserState.ToString();
            BarraProgreso.EditValue = e.ProgressPercentage;
        }
        #endregion
       
        private void MantenimientoEmpleados_FormClosing(object sender, FormClosingEventArgs e)
        {
            SystemUtils.RecordManagerPersona.UpdateList -= new LayerLogic.Persona.LPersona.AddObject(UpdateGrillaEmpleados);
        }

        private void GridView1CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.Name == "gcDocumento")
            {
                object obj = gridView1.GetRowCellValue(e.RowHandle, gcIdTipoDocumento);
                if (obj != null)
                {
                    EDocumento doc = SystemUtils.RecordManagerCommonList.GetDocument(Convert.ToInt64(obj.ToString()));
                    if (doc != null)
                    {

                        e.DisplayText = doc.Abreviatura;
                    }
                }
            }
            if (e.Column.Name == "gcSexo")
            {
                //gcSexo
                //gcIdSexo
                object obj = gridView1.GetRowCellValue(e.RowHandle, gcIdSexo);
                if (obj != null)
                {
                    ESexo s = SystemUtils.RecordManagerPersona.GetSexos(Convert.ToInt32(obj.ToString()));
                    if (s != null)
                    {
                        e.DisplayText = s.Descripcion;
                    }
                }
            }
            if (e.Column.Name == "gcEstado")
            {
                object obj = gridView1.GetRowCellValue(e.RowHandle, gcIdEstado);
                if (obj != null)
                {
                    EEstado est = SystemUtils.RecordManagerCommonList.GetEstadoById(Convert.ToInt32(obj.ToString()));
                    if (est != null)
                    {
                        e.DisplayText = est.Descripcion;
                    }
                }
            }

            if (e.Column.Name == "gcProfesion")
            {
                object obj = gridView1.GetRowCellValue(e.RowHandle, gcIdProfesion);
                if (obj != null) {
                    EProfesion pro = SystemUtils.RecordManagerCommonList.GetProfesion(Convert.ToInt32(obj.ToString()));
                    if (pro != null) {
                        e.DisplayText = pro.Descripcion;
                    }
                }
            }

            if (e.Column.Name == "gcGradoInstruccion") {
                object obj = gridView1.GetRowCellValue(e.RowHandle, gcIdGradoInstruccion);
                if (obj != null) {
                    EGradoInstruccion g = SystemUtils.RecordManagerCommonList.GetGradoInstruccion(Convert.ToInt32(obj.ToString()));
                    if (g != null) {
                        e.DisplayText = g.Descripcion;
                    }
                }
            }

            if (e.Column.Name == "gcEstadoCivil") {
                object obj = gridView1.GetRowCellValue(e.RowHandle, gcIdEstadoCivil);
                if (obj != null) {
                    EEstadoCivil ec = SystemUtils.RecordManagerCommonList.GetEstadoCivil(Convert.ToInt32(obj.ToString()));
                    if (ec != null) {
                        e.DisplayText = ec.Descripcion;
                    }
                }
            }

            if (e.Column.Name == "gcArea") {
                object obj = gridView1.GetRowCellValue(e.RowHandle, gcIdArea);
                if (obj != null) {
                    EAreas a = SystemUtils.RecordManagerCommonList.GetAreas(Convert.ToInt32(obj.ToString()));
                    if (a != null) {
                        e.DisplayText = a.Descripcion;
                    }
                }
            }

            if (e.Column.Name == "gcCargo") {
                object obj = gridView1.GetRowCellValue(e.RowHandle, gcIdCargo);
                if (obj != null) {
                    ECargos c = SystemUtils.RecordManagerCommonList.GetCargos(Convert.ToInt32(obj.ToString()));
                    if (c != null) {
                        e.DisplayText = c.Descripcion;
                    }
                }
            }
        }

        private void GridView1DoubleClick(object sender, EventArgs e)
        {
            EditarEmpleado();
        }

        private void GridView1Click(object sender, EventArgs e)
        {
            //EditarEmpleado();
        }

        private void GridView1MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (gridView1.GetFocusedRow() != null)
                {
                    popupMenu1.ShowPopup(new System.Drawing. Point(MousePosition.X, MousePosition.Y));
                }
            }
        }
    }
}